import Vue from 'vue';
import Vuex from 'vuex';
// 创建store实例对象之前, 必须把vuex注册成vue的插件
Vue.use(Vuex);
const store = new Vuex.Store({
    modules: {
        // 评论模块
        comments: {
            // 启用单独的命名空间，默认注册在全局命名空间
            namespaced: true,
            state: {
                comments: []
            },
            mutations: {
                // 删除评论
                delComment(state, id) {
                    state.comments = state.comments.filter(item => item.id != id)
                },
                // 新增评论
                addComment(state, comment) {
                    state.comments.unshift(comment);
                },
                // 获取默认评论列表
                getComments(state, comments) {
                    state.comments = comments
                }
            },
            actions: {
                // 异步获取默认的评论列表
                getInitComments({ commit }) {
                    const comments = [{
                        id: 1,
                        content: "人生若只如初见, 又何须伤感别离",
                        author: "duans",
                        posttime: new Date("2019/03/08").toLocaleDateString()
                    },
                    {
                        id: 2,
                        content: "若一切都已云烟成雨, 我能否变成淤泥,再一次沾染你?",
                        author: "duans",
                        posttime: new Date().toLocaleDateString()
                    }]
                    // 通过演示定时器模拟异步请求
                    setTimeout(() => {
                        commit('getComments', comments);
                    }, 2000);

                }
            },
            getters: {
                // 计算评论数量
                commentsCount: state => {
                    return state.comments.length
                }
            }
        }
    }

});

export default store